/* author: 贾星昊、陈帅 */

package com.example.demo.Activity;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.demo.Adapter.CurrencyAdapter;
import com.example.demo.Bean.Currency;
import com.example.demo.Bean.CurrencyState;
import com.example.demo.Bean.Userdata;
import com.example.demo.R;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class MainActivity extends AppCompatActivity {

    private BmobUser bmobUser; //登录用户信息
    private List<Userdata> userdataList = new ArrayList<Userdata>(); //各种货币信息及初始资金
    private List<Currency> currencyList = new ArrayList<>(); //货币名称
    private CurrencyAdapter currencyAdapter;
    private RecyclerView recyclerView;
    private GridLayoutManager layoutManager;
    private DrawerLayout mDrawerLayout;
    private NavigationView navView;
    private ActionBar actionBar;
    private ImageView img;
    private TextView uid;
    private TextView username;
    private FloatingActionButton myAsset, mQuit;
    private String closeA, closeB, closeC, closeD, closeE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        moveStatusbar();
        bmobUser = BmobUser.getCurrentUser(); //初始化用户数据
        initData();
        initView();
        setItemSelected();
    }

    public void DestroyTrashThread(){   //摧毁之前更新涨幅的线程
        Thread[] list = findAllThreads();
        List<Thread> Trash = new ArrayList<Thread>();
        for(int i = 0; i < list.length; i++){
            if(list[i].getName().equals("FlushRatioA"))
                Trash.add(list[i]);
            else if(list[i].getName().equals("FlushRatioB"))
                Trash.add(list[i]);
            else if(list[i].getName().equals("FlushRatioC"))
                Trash.add(list[i]);
            else if(list[i].getName().equals("FlushRatioD"))
                Trash.add(list[i]);
            else if(list[i].getName().equals("FlushRatioE"))
                Trash.add(list[i]);
        }
        for(int i = 0; i < Trash.size(); i++){
            Trash.get(i).interrupt();
        }
    }

    public static Thread[] findAllThreads() {   //返回所有线程列表
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
        /* 遍历线程组树，获取根线程组 */
        while ( group != null ){
            topGroup    = group;
            group        = group.getParent();
        }
        /* 激活的线程数加倍 */
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] slackList = new Thread[estimatedSize];
        /* 获取根线程组的所有线程 */
        int actualSize = topGroup.enumerate( slackList );
        /* copy into a list that is the exact size */
        Thread[] list = new Thread[actualSize];
        System.arraycopy( slackList, 0, list, 0, actualSize );
        return (list);
    }

    private void moveStatusbar() {
        if(Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.WHITE);
            window.setNavigationBarColor(Color.WHITE);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    void initData() {
        /*初始化用户基本信息*/
        if(bmobUser != null) {
            if (userdataList != null){
                userdataList.clear();
            }
            BmobQuery<Userdata> userdataBmobQueryBmobQuery = new BmobQuery<>();
            userdataBmobQueryBmobQuery.addWhereEqualTo("username", bmobUser.getUsername());
            userdataBmobQueryBmobQuery.order("-id");
            userdataBmobQueryBmobQuery.findObjects(new FindListener<Userdata>() {
                @Override
                public void done(List<Userdata> list, BmobException e) {
                    if (e == null) {
                        userdataList = list;
                    }
                }
            });
            /*初始化货币基本信息*/
            if (currencyList != null){
                currencyList.clear();
            }
            BmobQuery<Currency> currencyBmobQuery = new BmobQuery<>();
            currencyBmobQuery.findObjects(new FindListener<Currency>() {
                @Override
                public void done(List<Currency> list, BmobException e) {
                    currencyList = list;
                    currencyAdapter.setCurrencylist(list);
                }
            });
            BmobQuery<CurrencyState.A> aBmobQuery = new BmobQuery<>();
            aBmobQuery.order("Date"); //按时间排序
            aBmobQuery.findObjects(new FindListener<CurrencyState.A>() {
                @Override
                public void done(List<CurrencyState.A> list, BmobException e) {
                    closeA = list.get(list.size() - 1).getClose();
                }
            });
            BmobQuery<CurrencyState.B> bBmobQuery = new BmobQuery<>();
            bBmobQuery.order("Date"); //按时间排序
            bBmobQuery.findObjects(new FindListener<CurrencyState.B>() {
                @Override
                public void done(List<CurrencyState.B> list, BmobException e) {
                    closeB = list.get(list.size() - 1).getClose();
                }
            });
            BmobQuery<CurrencyState.C> cBmobQuery = new BmobQuery<>();
            cBmobQuery.order("Date"); //按时间排序
            cBmobQuery.findObjects(new FindListener<CurrencyState.C>() {
                @Override
                public void done(List<CurrencyState.C> list, BmobException e) {
                    closeC = list.get(list.size() - 1).getClose();
                }
            });
            BmobQuery<CurrencyState.D> dBmobQuery = new BmobQuery<>();
            dBmobQuery.order("Date"); //按时间排序
            dBmobQuery.findObjects(new FindListener<CurrencyState.D>() {
                @Override
                public void done(List<CurrencyState.D> list, BmobException e) {
                    closeD = list.get(list.size() - 1).getClose();
                }
            });
            BmobQuery<CurrencyState.E> eBmobQuery = new BmobQuery<>();
            eBmobQuery.order("Date"); //按时间排序
            eBmobQuery.findObjects(new FindListener<CurrencyState.E>() {
                @Override
                public void done(List<CurrencyState.E> list, BmobException e) {
                    closeE = list.get(list.size() - 1).getClose();
                }
            });
        }
    }

    void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(Color.BLACK);//字体为黑色
        setSupportActionBar(toolbar);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); //禁止侧滑
        navView = (NavigationView) findViewById(R.id.nav_view);
        myAsset = (FloatingActionButton) findViewById(R.id.myasset);
        mQuit = (FloatingActionButton) findViewById(R.id.quit);
        if(bmobUser != null) {
            myAsset.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(MainActivity.this, AssetActivity.class);
                    intent.putExtra("userDataList",(Serializable)userdataList);
                    intent.putExtra("closeA", closeA);
                    intent.putExtra("closeB", closeB);
                    intent.putExtra("closeC", closeC);
                    intent.putExtra("closeD", closeD);
                    intent.putExtra("closeE", closeE);
                    startActivity(intent);
                }
            });
        }
        mQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exit(MainActivity.this);
            }
        });
        actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        layoutManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(layoutManager);
        currencyAdapter = new CurrencyAdapter(currencyList, this);
        recyclerView.setAdapter(currencyAdapter);
    }

    void setItemSelected() {
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_signout:
                        BmobUser.logOut();
                        mDrawerLayout.closeDrawer(GravityCompat.START);
                        break;
                    case R.id.nav_ours:
                        Toast.makeText(MainActivity.this,"作品由贾星昊和陈帅共同完成！",Toast.LENGTH_LONG).show();
                        break;
                    default:break;
                }
                return true;
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                img = (ImageView) findViewById(R.id.icon_image);
                uid = (TextView) findViewById(R.id.uid);
                username = (TextView) findViewById(R.id.username);
                bmobUser = BmobUser.getCurrentUser(); //获取用户状态
                if(bmobUser == null) {
                    uid.setText("单点头像");
                    username.setText("登录注册");
                    navView.getMenu().findItem(R.id.nav_money).setTitle("xxx $");
                    navView.getMenu().findItem(R.id.nav_location).setTitle("xxxx");
                    navView.getMenu().findItem(R.id.nav_call).setTitle("xxxxxxxxxxx");
                    navView.getMenu().findItem(R.id.nav_mail).setTitle("xxxxxxxx@xxx.com");
                    navView.getMenu().findItem(R.id.nav_signout).setTitle("请先登录");
                    img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent=new Intent(MainActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }); //登录注册事件
                } else {
                    img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Random rand = new Random();
                            int index = rand.nextInt(7);
                            int rid = getResources().getIdentifier("nav_icon" + String.valueOf(index),"drawable", getPackageName());
                            img.setImageDrawable(getResources().getDrawable(rid));
                        }
                    });
                    uid.setText("UID: " + bmobUser.getObjectId());
                    username.setText("@" + bmobUser.getUsername());
                    navView.getMenu().findItem(R.id.nav_money).setTitle(getMoney());
                    navView.getMenu().findItem(R.id.nav_location).setTitle("中国 北京");
                    navView.getMenu().findItem(R.id.nav_call).setTitle("尚未绑定手机号");
                    if(bmobUser.getMobilePhoneNumber() != null && !bmobUser.getMobilePhoneNumber().equals(""))
                        navView.getMenu().findItem(R.id.nav_call).setTitle(bmobUser.getMobilePhoneNumber());
                    navView.getMenu().findItem(R.id.nav_mail).setTitle(bmobUser.getEmail());
                }
                break;
            case R.id.general:
                Collections.sort(currencyList, new Comparator<Currency>() {
                    @Override
                    public int compare(Currency c1, Currency c2) {
                        return c1.getId().compareTo(c2.getId());
                    }
                });
                DestroyTrashThread();
                currencyAdapter.notifyDataSetChanged();
                break;
            case R.id.increase:
                Collections.sort(currencyList, new Comparator<Currency>() {
                    @Override
                    public int compare(Currency c1, Currency c2) {
                        double ratio1, ratio2;
                        try{
                            ratio1 = Double.parseDouble(c1.getLastRadio());
                        }catch (Exception e){
                            return c1.getId().compareTo(c2.getId());
                        }
                        try{
                            ratio2 = Double.parseDouble(c2.getLastRadio());
                        }catch (Exception e){
                            return c1.getId().compareTo(c2.getId());
                        }
                        double gap = ratio1 - ratio2;
                        while (Math.abs(gap) < 1) gap *= 10;
                        return (int)gap;
                    }
                });
                DestroyTrashThread();
                currencyAdapter.notifyDataSetChanged();
                break;
            case R.id.decrease:
                Collections.sort(currencyList, new Comparator<Currency>() {
                    @Override
                    public int compare(Currency c1, Currency c2) {
                        double ratio1, ratio2;
                        try{
                            ratio1 = Double.parseDouble(c1.getLastRadio());
                        }catch (Exception e){
                            return c1.getId().compareTo(c2.getId());
                        }
                        try{
                            ratio2 = Double.parseDouble(c2.getLastRadio());
                        }catch (Exception e){
                            return c1.getId().compareTo(c2.getId());
                        }
                        double gap = ratio2 - ratio1;
                        while (Math.abs(gap) < 1) gap *= 10;
                        return (int)gap;
                    }
                });
                DestroyTrashThread();
                currencyAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
        return true;
    }

    String getMoney() {
        double money = 0;
        for(int i = 0; i < userdataList.size(); i++) {
            if(userdataList.get(i).getId().equals("###")) {
                money += Double.parseDouble(userdataList.get(i).getCount());
                break;
            }
        }
        DecimalFormat decimalFormat =new DecimalFormat("0.0000");
        return decimalFormat.format(money) + " $";
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    } //返回后重新加载

    private void exit(Context context){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

}